package com.joney.mq.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;

import javax.jms.ConnectionFactory;

/**
 * @author wangxianchen
 * @create 2018-03-06
 * @desc 声明2种模式的Listener, 默认为Queue点对点的
 */
@Configuration
@EnableJms
public class JmsConfiguration {

    // topic模式的ListenerContainer
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(activeMQConnectionFactory);
        return bean;
    }

    // queue模式的ListenerContainer
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setConnectionFactory(activeMQConnectionFactory);
        bean.setMessageConverter(myMessageConverter()); //使用消息转换器
        return bean;
    }

    //自定义消息转换器,非必需
    @Bean
    public MessageConverter myMessageConverter() {
        //MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
        //converter.setTargetType(MessageType.OBJECT);
        //converter.setTypeIdPropertyName("type");
        return new MyMessageConverter();
    }

}
